<template>
    <div class="table-container" v-loading="loading">
        <div style="display: flex;justify-content:right;">
            <!-- <el-button  type="primary" @click="printObj">打印</el-button> -->
            <!-- <el-button @click="createAndUploadPDF" :loading="uploading">生成并上传PDF</el-button> -->
        </div>
        <div id="printTable">
            <h2 style="text-align: center">凉山彝族自治州第一人民医院</h2>
            <h3 style="text-align: center">重症医学科血液净化治疗记录单</h3>
            <div class="baseInfo">
                <div>姓名：{{ baseInfo?.NAME || "" }}</div>
                <div>性别：{{ baseInfo?.SEX || "" }}</div>
                <div>年龄：{{ baseInfo?.AGE || "" }}</div>
                <div>床号：{{ baseInfo?.BEDNAME || "" }}</div>
                <div>住院号：{{ baseInfo?.ADMISSIONNUMBER || "" }}</div>
                <div>日期：{{ baseInfo?.INFODATE || "" }}</div>
                <div>透析器型号：{{ baseInfo?.MTYPE || "" }}</div>
            </div>
            <table class="bordered-table">
                <!-- 表格内容保持不变 -->
                <!-- 第一行表头 -->
                <thead class="header">
                    <tr>
                        <template v-for="(header, index) in headers" :key="index">
                            <th v-if="!header.children && header.title !== 'MODS'" :rowspan="header.rowspan || 1"
                                :colspan="header.colspan || 1">
                                {{ header.title }}
                            </th>
                            <th v-else-if="header.title == 'MODS'" :rowspan="header.rowspan || 1"
                                :colspan="header.colspan || 1">
                                <div v-for="item in header.title.split('')">{{ item }}</div>
                            </th>
                            <th v-else :colspan="header.colspan || 1" :rowspan="header.rowspan || 1">
                                {{ header.title }}
                            </th>
                        </template>
                    </tr>

                    <!-- 第二行表头 -->
                    <tr>
                        <template v-for="(header, index) in headers" :key="index">
                            <template v-if="header.children">
                                <template v-for="(child, childIndex) in header.children" :key="childIndex">
                                    <th :colspan="child.colspan || 1" v-if="child.title !== ''">
                                        {{ child.title }}
                                    </th>
                                </template>
                            </template>
                        </template>
                    </tr>

                    <!-- 第三行表头 -->
                    <tr style="font-size: 10px">
                        <template v-for="(header, index) in headers" :key="index">
                            <template v-if="header.children">
                                <template v-for="(child, childIndex) in header.children" :key="childIndex">
                                    <template v-for="(childItem, childIndex) in child.children" :key="childIndex">
                                        <th>
                                            {{ childItem.title }}
                                        </th>
                                    </template>
                                </template>
                            </template>
                        </template>
                    </tr>
                </thead>

                <!-- 表格内容 -->
                <tbody>
                    <tr v-for="(item, rowIndex) in tableData" :key="rowIndex">
                        <td v-for="(value, key) in item" :key="key">
                            <span v-if="key != 28">{{ value }}</span>
                            <span v-else>
                                <img :src="'data:image/gif;base64,' + value" alt="" width="50px" height="30px" />
                            </span>
                        </td>
                    </tr>
                </tbody>
            </table>
            
            <!-- 审核人区域 - 固定在右下角 -->
            <div class="audit-area">
                <div class="audit-box">
                    <div class="audit-label">审核人：</div>
                    <div class="audit-signature"><img :src="imgsrc" alt="" class="signature-image" /></div>
                </div>
            </div>
            
            <!-- PDF 预览区域 -->
            <!-- <div v-if="pdfBlobUrl" style="margin-top: 20px;">
                <h3>PDF 预览:</h3>
                <iframe :src="pdfBlobUrl" width="100%" height="500px"></iframe>
            </div> -->
        </div>
    </div>
</template>

<script setup>
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import { getBloodAPI, upload } from "../api/book.js";
import dayjs from "dayjs";
import { ElMessage } from 'element-plus';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
import { useRoute } from "vue-router";
const headers = [
    {
        title: "时间",
        key: "system",
        rowspan: 2,
    },
    {
        title: "模式",
        key: "system",
        rowspan: 2,
    },
    {
        title: "核查无误",
        key: "system",
        rowspan: 2,
    },
    {
        title: "流速调整",
        key: "flow",
        colspan: 8,
        children: [
            { title: "流速(ml/min)", key: "flow1" },
            { title: "置换液(ml/h)", key: "flow2" },
            { title: "透析液(ml/h)", key: "flow3" },
            { title: "前稀释", key: "flow3" },
            { title: "后稀释", key: "flow3" },
            { title: "分浆速度(ml/min)", key: "flow3" },
            { title: "碳酸氢钠(ml/h)", key: "flow3" },
            { title: "脱水速度(ml/h)", key: "flow3" },
        ],
    },
    {
        title: "抗凝方式",
        key: "flow",
        colspan: 4,
        children: [
            { title: "肝素(U/h)", key: "flow2" },
            { title: "萘莫司他(mg/h)", key: "flow3" },
            { title: "枸橼酸(ml/h)", key: "flow3" },
            { title: "10%葡萄糖酸钙(ml/h)", key: "flow3" },
        ],
    },
    {
        title: "压力检测",
        key: "flow",
        colspan: 3,
        children: [
            { title: "动脉压", key: "flow2" },
            { title: "静脉压", key: "flow3" },
            { title: "跨膜压", key: "flow3" },
        ],
    },
    {
        title: "酸碱电解质检测",
        key: "flow",
        colspan: 4,
        children: [
            { title: "K+", key: "flow2" },
            { title: "HCO3-", key: "flow3" },
            { title: "CaA", key: "flow3" },
            { title: "PCa", key: "flow3" },
        ],
    },
    {
        title: "下机状态",
        key: "flow",
        colspan: 1,
        children: [{ title: "管路凝血(是否)", key: "flow2" }],
    },
    {
        title: "签名",
        key: "system",
        rowspan: 2,
    },
];
const pdfBlobUrl = ref('');
const uploading = ref(false);

const route = useRoute();

// 生成并上传 PDF 文件
async function createAndUploadPDF() {
    console.log("开始创建PDF");
    uploading.value = true;

    try {
        // 获取要转换为PDF的元素
        const element = document.getElementById('printTable');

        if (!element) {
            console.error('找不到ID为printTable的元素');
            ElMessage.error('找不到打印内容');
            uploading.value = false;
            return;
        }

        // 使用 html2canvas 将HTML元素转换为canvas
        const canvas = await html2canvas(element, {
            scale: 2, // 降低scale以减少内存使用
            useCORS: true,
            logging: false,
            width: element.offsetWidth,
            height: element.offsetHeight,
            scrollX: 0,
            scrollY: 0,
            // 添加更多配置选项以提高兼容性
            allowTaint: true,
            foreignObjectRendering: false
        });

        // 检查canvas是否成功创建
        if (!canvas) {
            throw new Error('Canvas创建失败');
        }

        // 将canvas转换为图片数据
        const imgData = canvas.toDataURL('image/png');
        
        // 检查图片数据是否有效
        if (!imgData || imgData === 'data:,') {
            throw new Error('图片数据无效');
        }

        // 创建PDF文档 (A4尺寸: 210mm x 297mm)
        const pdf = new jsPDF('p', 'mm', 'a4');

        // 计算图片尺寸以适应A4页面
        const imgWidth = 210 - 20; // 减少边距
        const pageHeight = 295;
        const imgHeight = (canvas.height * imgWidth) / canvas.width;

        let heightLeft = imgHeight;
        let position = 10; // 增加顶部边距

        // 添加第一页
        pdf.addImage(imgData, 'PNG', 10, position, imgWidth, imgHeight);
        heightLeft -= (pageHeight - 20);

        // 如果内容超过一页，继续添加新页面
        while (heightLeft > 0) {
            pdf.addPage();
            position = -(heightLeft - (pageHeight - 20));
            pdf.addImage(imgData, 'PNG', 10, position, imgWidth, imgHeight);
            heightLeft -= (pageHeight - 20);
        }

        // 将PDF转换为Blob（文件流形式）
        const pdfBlob = pdf.output('blob');
        
        // 创建预览 URL（可选）
        pdfBlobUrl.value = URL.createObjectURL(pdfBlob);
        window.open(pdfBlobUrl.value);
        // 直接上传PDF文件流
        // await uploadPDF(pdfBlob);
        
        // ElMessage.success('PDF生成并上传成功');

    } catch (error) {
        console.error('创建PDF出错:', error);
        // ElMessage.error('PDF生成或上传失败: ' + error.message);
    } finally {
        uploading.value = false;
    }
}

// 上传PDF文件
async function uploadPDF(pdfBlob) {
    try {
        console.log('PDF Blob:', pdfBlob);
        console.log('PDF Blob 类型:', pdfBlob instanceof Blob);
        console.log('PDF Blob 大小:', pdfBlob.size);
        
        // 检查Blob是否有效
        if (!pdfBlob || pdfBlob.size === 0) {
            throw new Error('PDF文件无效');
        }
        
        // 直接传递 Blob 对象和 docId
        const res = await upload({
            file: pdfBlob,
            docId: docId.value
        });
        
        console.log('上传结果:', res);
        // ElMessage.success('PDF上传成功');
        return res;

    } catch (error) {
        // console.error('上传出错:', error);
        ElMessage.error('PDF上传失败: ' + error.message);
        console.log('上传失败,',error);
        throw error;
    }
}

// 获取图片
const getImg = async (url) => {
    try {
        if (!url) {
            console.error('传入的图片数据为空');
            return { success: false, message: '图片数据为空' };
        }
        
        // 修复语法错误：应该是 state.imgsrc 而不是 imgsrc.value
        state.imgsrc = `data:image/gif;base64,${url}`;
        // console.log('图片已设置成功');
        createAndUploadPDF()
        // return { success: true, message: '图片设置成功' };
    } catch (error) {
        console.error('设置图片时出错:', error);
        ElMessage.error('失败:');
        return { success: false, message: '设置图片失败' };
    }
};

const state = reactive({
    selectedYear: [dayjs().format("YYYY-MM"), dayjs().format("YYYY-MM")],
    tableData: [],
    loading: false,
    show: false,
    docId: "",
    baseInfo: {},
    imgsrc: "", // 图片源
    // printObj: {
    //     id: "printTable",
    //     preview: false,
    //     previewTitle: "打印预览",
    //     popTitle: "good print",
    //     beforeOpenCallback(vue) {
    //         console.log("打开之前");
    //     },
    //     openCallback(vue) {
    //         console.log("执行了打印");
    //     },
    //     closeCallback(vue) {
    //         console.log("关闭了打印工具");
    //     },
    // },
});

// 为桌面应用提供更明确的方法名
const setSignatureImage = async (base64Data) => {
    return await getImg(base64Data);
};

const { selectedYear, tableData, loading, docId, baseInfo, imgsrc, show } = toRefs(state);

onMounted(() => {
    if (route.query.docId) {
        docId.value = route.query.docId;
    }
    // 将方法挂载到window对象
    window.getImg = getImg;
    window.setSignatureImage = setSignatureImage;
    window.printObj = printObj;
    getTableData();
    // createAndUploadPDF()
});
const printObj = () => {
  // 使用 Element Plus 的打印指令功能
//   if (state.printObj && typeof state.printObj.onPrint === 'function') {
//     state.printObj.onPrint();
//   } else {
    // 备用方案：直接调用浏览器打印
    window.print();
//   }
};

const getTableData = async () => {
    if (docId.value) {
        console.log(docId.value);
    }
    const res = await getBloodAPI(docId.value || 12578);
    baseInfo.value = res.patientInfo[0];
    tableData.value = res.reportList;
    imgsrc.value ='data:image/gif;base64,'+res.patientInfo[0].signPic
};

defineExpose({
    // printObj,
    getImg,
    setSignatureImage,
    printObj
});

// 修复后的 watch
watch(() => route.query.docId, (newVal) => {
    if (newVal) {
        docId.value = newVal;
        getTableData();
    }
}, { immediate: true });
</script>

<style scoped>
.table-container {
    width: 100%;
    height: 100%;
    position: relative;
}

.operate {
    display: flex;
}

.bordered-table {
    border-collapse: collapse;
    border: 1px solid black;
    width: 100%;
}

.baseInfo {
    display: flex;
    justify-content: space-between;
}

.bordered-table th,
.bordered-table td {
    border: 1px solid black;
    box-sizing: border-box;
}

tbody th,
tbody td {
    border: 1px solid black;
    padding: 6px;
    text-align: center;
}

.bordered-table th {
    font-size: 13px;
}

/* 审核人区域样式 - 固定在右下角 */
.audit-area {
    /* position: absolute;
    bottom: 10px;
    right: 20px;
    z-index: 10; */
}

.audit-box {
    /* border: 2px solid #ff0000; */
    padding: 10px;
    background-color: #fff;
    border-radius: 4px;
    min-width: 120px;
    text-align: center;
    display: flex;
    justify-content: right;
    /* flex-direction: column; */
    align-items: center;
}

.audit-label {
    font-weight: bold;
    margin-bottom: 5px;
    font-size: 18px;
}

.audit-signature {
    font-style: italic;
    font-size: 14px;
    color: #333;
}

/* 签名图片样式 */
.signature-image {
    max-width: 100px;
    max-height: 50px;
    width: auto;
    height: auto;
    object-fit: contain;
}

#printTable{
    width: 100%;
    /* min-height: 90vh; */
    /* position: relative; */
}

@media print {
    body {
        margin: 0;
        padding: 0;
        width: 100vw;
        position: relative;
    }

    #printTable {
        width: 100% !important;
        max-width: 100% !important;
        transform-origin: 0 0;
        /* position: relative; */
    }

    .bordered-table {
        width: 100%;
    }

    .h2 {
        width: 100%;
    }

    .input {
        box-shadow: none !important;
    }

    td {
        font-size: 9pt;
        text-align: center;
    }

    .bordered-table td {
        font-size: 9pt;
        box-sizing: border-box;
        padding: 2pt;
        min-width: 12pt;
        max-width: 60pt;
        print-color-adjust: exact;
        page-break-inside: avoid;
        word-break: break-all;
    }
    
    /* 打印时也固定在右下角 */
    .audit-area {
        /* position: absolute;
        bottom: 20px;
        right: 20px;
        z-index: 10; */
    }
    
    .audit-box {
        /* border: 2px solid #ff0000; */
        padding: 10px;
        background-color: #fff;
        border-radius: 4px;
        min-width: 120px;
        text-align: center;
        display: flex;
        /* flex-direction: column; */
        justify-content: right;
        align-items: center;
    }
    
    /* 打印时的签名图片样式 */
    .signature-image {
        max-width: 100px;
        max-height: 50px;
        width: auto;
        height: auto;
        object-fit: contain;
    }
}
</style>